<?php

namespace App\Services\User\RoleGroup;


use App\Models\User\RoleGroup;
class RoleGroupLogic
{
    // 增加一条角色组记录
    public function add(array $data): array
    {
        $data['status'] = '1';
        try{
            $res = RoleGroup::insert($data);
        }catch (\Exception $e) {
            // 当唯一键重复等报错时
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($res, '成功增加一条角色组记录', '增加一条角色组记录失败');
    }
    // 禁用一个角色组
    public function stop(array $data): array
    {

        if(!empty($data['id'])){
        $where[]=['id','=',$data['id']];
        }
        if(!empty($data['name'])){
        $where[]=['name','=',$data['name']];
        }

        $res = RoleGroup::where($where)->update(['status'=>'0']);
        return auto_return($res, '成功禁用一个角色组', '禁用一个角色组失败');
    }
    // 按分页获取角色组列表
    public function list(array $data): array
    {
        if(isset($data['status'])){
            $_where[]=['status','=',$data['status']];
        }
        if(isset($_where)){
            $list = RoleGroup::where($_where)
                ->paginate($data['list_rows'], null, null, $data['page'])
                ->toArray();
        }else{
            $list = RoleGroup::paginate($data['list_rows'], null, null, $data['page'])
                ->toArray();
        }

        return auto_return_page($list, '成功获取角色列表', '获取角色列表失败');
    }
    // 编辑用户角色组信息
    public function edit(array $data): array
    {
        $_where[] = ['id','=',$data['id']];
        try{
            $res = RoleGroup::where($_where)
                ->update($data);
        }catch (\Exception $e) {
            // 当唯一键重复等报错时
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($res, '成功编辑角色组信息', '编辑角色组信息失败');
    }
    // 根据role_group_ids解析成角色ids
    public function roleGroupIdsToRoleIds(array $data): array
    {
        $_where['id'] = ['in', $data['group_ids']];
        $_where['status'] = 1;
        $list = RoleGroup::where($_where)->pluck('role_ids')->toArray();

        if (!$list) { return null_data(null, '没有相关数据'); };
        $ids = '';
        foreach($list as $k => $v){
            $ids .= $v . ',';
        }
        $idsArr = array_unique( explode(',', trim($ids, ',')) );
        $ids = implode(',', $idsArr);
        return auto_return($ids, '成功解析角色组信息', '解析角色组信息失败');
    }
}